package com.qf.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping(value="all",method = RequestMethod.GET)
    public String all(HttpServletRequest request, HttpServletResponse response){
       List<User> list= userService.selectAll();
       request.setAttribute("ulist",list);
        return  "show";
    }
    @RequestMapping(value = "all2/{page}",method =RequestMethod.GET )
    public  ModelAndView all2(ModelAndView mv,@PathVariable("page")int page){
        PageHelper.startPage(page,2);
        List<User> list= userService.selectAll();
        PageInfo<User> pi=new PageInfo<>(list);
        mv.addObject("ulist",pi);
        mv.setViewName("show");
        return mv;
    }
    @RequestMapping("del/{id}")
    public String delete(@PathVariable("id")int id){
        userService.deleteOne(id);
        return "forward:/user/all2/1";
    }
    @RequestMapping("one/{id}")
    public String selectOne(@PathVariable("id")int id, Model model){
        User user = userService.selectOne(id);
        model.addAttribute("user",user);
        return "update";
    }
    @RequestMapping(value = "upd",method = RequestMethod.POST)
    public String update(User user){
        System.out.println("user = " + user);
       /* String genders=user.getGender();
        String gender="";
        try {
             gender=new String(genders.getBytes("iso-8859-1"),"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        user.setGender(gender);*/
        userService.update(user);
        return "redirect:/user/all2/1";
    }

    @RequestMapping("/admin")
    public String admin(){

        return "admin";
    }
}
